﻿jQuery.usi.tools = {
    //调用swf控件上传附件参数有id与options，具体options参数参见uploadify上传组件的参数说明
    uploadFile: function (id, options) {
        var setting = {
            'swf': '/lib/uploadify/uploadify.swf',
            'cancelImg': '/lib/uploadify/uploadify-cancel.png', //取消按钮的图片
            'buttonText': '添加附件', //选择按钮的文本
            'sizeLimit': '1999MB',
            'onUploadError': function (file, errorCode, errorMsg, errorString) {
                layer.alert(file.toString() + ";" + errorCode.toString() + ";" + errorMsg.toString() + ";" + errorString.toString());
            },
            'fileSizeLimit': '1999MB'
            // 'fileTypeExts': '*.doc;*.pdf;*.rar',
        };
        $.extend(true, setting, options);
        var file = jQuery.usi.core.getJqueryById(id).uploadify(setting);
        jQuery.usi.core.getJqueryById(id).next().remove();
        return file;
    },
    //获取条件
    getQueryData: function (id) {
        var where = [];
        if (id.indexOf("#") < 0) {
            id = "#" + id;
        }
        $(id).find("input[type='text'],input[type='hidden'],select").each(function (index, item) {
            where.push($(item));
        });
        return jQuery.usi.tools.bindDataTable.getsearchWhereForm(where);
    },
    //获取文件大小
    getFileSize: function (num) {
        if (isNaN(num)) {
            return false;
        }
        num = parseInt(num);
        var units = [" B", " KB", " MB", " GB"];
        for (var i = 0; i < units.length; i += 1) {
            if (num < 1024) {
                num = num + "";
                if (num.indexOf(".") != -1 && num.indexOf(".") != 3) {
                    num = num.substring(0, 4);
                } else {
                    num = num.substring(0, 3);
                }
                break;
            } else {
                num = num / 1024;
            }
        }
        return num + units[i];
    },
    getFileCache: function (fileName) {
        return jQuery.usi.core.fileCachePath + fileName;
    },
    //上传单个文件，参数有id,type,showid,callback
    uploadSingleFile: function (config) {
        jQuery.usi.core.getJqueryById(config.id).parents("form").ajaxSubmit({
            url: "/FileUpload/SingleUpload",
            dataType: "json",
            data: { Type: config.type },
            success: function (data) {
                if (data.success) {
                    if (!jQuery.usi.core.isNullOrEmpty(data.msg)) {
                        layer.alert(data.msg)
                    }
                    if (!jQuery.usi.core.isNullOrEmpty(config.showId)) {
                        jQuery.usi.core.getJqueryById(config.showId).attr("src", jQuery.usi.tools.getFileCache(data.Data));
                    }
                    if (jQuery.usi.core.isMethod(config.callback)) {
                        config.callback(data.data);
                    }
                } else {
                    layer.alert(data.msg);
                }
            }
        });
    },
    assignForZTree: function (item) {
        var node = {
            children: []
        };
        $.extend(true, node, { id: item.id });
        $.extend(true, node, { checked: item.showChecked });
        $.extend(true, node, { click: item.click });
        $.extend(true, node, { icon: item.icon });
        $.extend(true, node, { iconSkin: item.iconSkin });
        $.extend(true, node, { isParent: item.isParent });
        $.extend(true, node, { name: item.name });
        $.extend(true, node, { open: item.open });
        $.extend(true, node, { target: item.target });
        $.extend(true, node, { url: item.url });
        $.extend(true, node, { param: item.param });
        if (item.children != null) {
            $.each(item.children, function (index, childNodes) {
                node.children.push(jQuery.usi.tools.assignForZTree(childNodes));
            });
        }
        return node;
    },
    initForZTree: function (id, setting, data) {
        if (jQuery.usi.core.isArray(data)) {
            var dataArray = [];
            $.each(data, function (index, item) {
                dataArray.push(jQuery.usi.tools.assignForZTree(item));
            });
            return $.fn.zTree.init($("#" + id), setting, dataArray);
        } else {
            data = jQuery.usi.tools.assignForZTree(data);
            return $.fn.zTree.init($("#" + id), setting, data);
        }
    },
    //设置时间格式icalendar.js
    icalendar: function (id, config) {
        var input = jQuery.usi.core.getJqueryById(id);
        input.addClass("date");
        input.unbind("keyup");
        input.bind("keyup", function (event) {
            if (event.keyCode == 8 || event.keyCode == 46) {
                input.val("");
            }
        });
        config = config == null ? { showMonths: 1 } : config;
        config.showMonths = config.showMonths == null ? 1 : config.showMonths;
        config.symbiont = false;
        config.selectClose = config.selectClose == null ? true : config.selectClose;
        config.DefaultDate = config.DefaultDate == null ? false : config.DefaultDate;
        input.icalendar(config);
        if (config.DefaultDate) {
            input.val(new Date().format("yyyy-M-d"));
        }
        input.attr("readonly", true);
    },
    form: {
        loadData: function (config) {
            var url = config.url;
            var param = config.param == null ? {} : config.param;
            var callback = config.callback;
            var form;
            if (config.id.indexOf("#") >= 0) {
                form = $(config.id);
            } else {
                form = $("#" + config.id);
            }
            if (form != null) {
                if (config.data != null) {
                    form.json2form(config.data);
                    if (jQuery.usi.core.isMethod(callback)) {
                        callback(config.data);
                    }
                } else {
                    jQuery.usi.core.post(url, param, false, function (resultData) {
                        form.json2form(resultData.data);
                        if (jQuery.usi.core.isMethod(callback)) {
                            callback(resultData.data);
                        }
                    });
                }
            }
        },
        submit: function (config) {
            var url = config.url;
            var callback = config.callback;
            var form;
            if (config.id.indexOf("#") >= 0) {
                form = $(config.id);
            } else {
                form = $("#" + config.id);
            }
            var param = config.param == null ? {} : config.param;
            if (form != null) {
                if (jQuery.usi.tools.form.validateForm(config.id)) {
                    var json = form.form2json();
                    param.data = json;
                    jQuery.usi.core.post(url, param, false, function (resultData) {
                        if (jQuery.usi.core.isMethod(callback)) {
                            callback(resultData);
                        }
                    });
                }
            }
        },
        //获取某个元素下所有需要验证的元素
        getValidateElement: function (doc) {
            return $(doc).find("input[isvalidate=true],select[isvalidate=true],textarea[isvalidate=true],span[isvalidate=true],div[isvalidate=true]");
        },

        //验证渲染加个* 并且绑定输入修改事件
        renderValidate: function (doc) {
            jQuery.usi.tools.form.getValidateElement(doc).each(function (index, item) {
                var warnMsg = $('<span class="c-red">*</span>');
                var event = "blur";
                if (item.type == "select-one") {
                    event = "change";
                } else if (item.type == "hidden") {
                    warnMsg.hide();
                } else {
                    //判断div与span
                }
                $(item).bind(event + " validate", function (item2) {
                    var result = jQuery.usi.tools.form.getValidateResult($(this));
                    if (result.success) {
                        warnMsg.css("visibility", "hidden");
                    } else {
                        warnMsg.css("visibility", "inherit");
                    }
                });
                $(item).parent().prev().append(warnMsg);
                var result = jQuery.usi.tools.form.getValidateResult($(item));
                if (result.success) {
                    warnMsg.css("visibility", "hidden");
                } else {
                    warnMsg.css("visibility", "inherit");
                }
            });
        },
        //验证某个元素返回验证结果
        getValidateResult: function (item) {
            item = $(item);
            var validate = {
                isvalidate: item.attr("isvalidate"),   //是否验证
                type: item.attr("validatetype"), //验证类型
                msg: item.attr("validatemsg"), //消息
                value: item.val()
            };
            return jQuery.usi.tools.form.regularValidate({ value: validate.value, msg: validate.msg, type: validate.type });
        },
        //--表单验证
        validateForm: function (formId) {
            var success = true;
            if (formId.indexOf("#") < 0) {
                formId = "#" + formId;
            }
            jQuery.usi.tools.form.getValidateElement($(formId)).each(function (index, item) {
                var result = jQuery.usi.tools.form.getValidateResult(item);
                if (!result.success) {
                    layer.alert(result.msg);
                    success = false;
                    item.focus();
                    return false;
                }
            })
            return success;
        },
        regularValidate: function (config) {
            //正则验证
            var result = {
                success: false,
                msg: ""
            };
            var value = jQuery.usi.core.isNullOrEmpty(config.value) ? "" : config.value.Trim();
            switch (config.type) {
                case "PostNo":
                    result.success = /^[0-9]\d{5}$/.test(value);
                    result.msg = "邮政编码格式错误";
                    break; ////邮政编码
                case "Email":
                    result.success = /^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/.test(value);
                    result.msg = "电子邮件格式错误";
                    break; //邮件
                case "Mobile":
                    result.success = /(13[0-9]{9})|(17[0-9]{9})|(18[0-9]{9})|(14[0-9]{9})|(15[0-9]{9})/.test(value);
                    result.msg = "手机号格式错误";
                    break; //手机号
                case "Phone":
                    result.success = /^\d{7,8}$/.test(value);
                    result.msg = "电话号码格式错误";
                    break;  //电话号码
                case "PhoneMobile":
                    result.success = /(^\d{7,8}$)|(^(1[0-9]{10})$)|(^\d{10,12}$)|(^\d{3,4}-\d{7,8}$)/.test(value);
                    result.msg = "联系电话输入错误如'0591-88888888'或'13950888888'";
                    break; //移动电话
                case "QQ":
                    result.success = /^[0-9]+$/.test(value);
                    result.msg = "QQ号码格式错误";
                    break;   // QQ 号码
                case "OnlyNumber":
                    result.success = /^[0-9\ ]+$/.test(value);
                    result.msg = "只允许输入数字";
                    break;     //只能数字
                case "IsDecimal":
                    result.success = /^[0-9]+\.?[0-9]*$/.test(value);
                    result.msg = "只允许输入带小数的正整数";
                    break; //带小数正整数
                case "Double":
                    result.success = /^-?(0|[1-9][0-9]*)\.[0-9]+$/.test(value);
                    result.msg = "只允许输入浮点数";
                    break; //浮点数
                case "PDouble":
                    result.success = /^(0|[1-9][0-9]*)\.[0-9]+$/.test(value);
                    result.msg = "只允许输入正浮点数";
                    break; //正浮点数
                case "NoSpecialCaracters":
                    result.success = /^[0-9a-zA-Z]+$/.test(value);
                    result.msg = "不允许输入特殊字符";
                    break;    //不包含其他特殊符号
                case "OnlyLetter":
                    result.success = /^[a-zA-Z\ \']+$/.test(value);
                    result.msg = "只允许输入a-z的字符";
                    break; 	  //只能字母
                case "Integer":
                    result.success = /^(0|-?[1-9][0-9]*)$/.test(value);
                    result.msg = "只允许输入整数";
                    break; //匹配整数
                case "PInteger":
                    result.success = /^(0|[1-9][0-9]*)$/.test(value);
                    result.msg = "只允许输入正整数";
                    break; //匹配正整数
                case "Chinese":
                    result.success = /^[\u4e00-\u9fa5]*$/.test(value);
                    result.msg = "只允许输入中文";
                    break; //匹配中文
                case "CarsNumber":
                    result.success = /^[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5}$/.test(value);
                    result.msg = "车牌号格式不对";
                    break; //车牌号验证
                case "IdCard":
                    var idNum = value;
                    //身份号码位数及格式检验
                    var re;
                    var len = idNum.length;
                    //身份证位数检验
                    if (len != 15 && len != 18) {
                        result.msg = "身份证号码位数不对";
                        result.success = false;
                        break;
                    } else if (len == 15) {
                        re = new RegExp(/^(\d{6})()?(\d{2})(\d{2})(\d{2})(\d{3})$/);
                    } else {
                        re = new RegExp(/^(\d{6})()?(\d{4})(\d{2})(\d{2})(\d{3})([0-9xX])$/);
                    }
                    var area = {
                        11: "北京", 12: "天津", 13: "河北", 14: "山西",
                        15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江", 31: "上海",
                        32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西",
                        37: "山西", 41: "河南", 42: "湖北", 43: "湖南", 44: "广东",
                        45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州",
                        53: "云南", 54: "西藏", 61: "陕西", 62: "甘肃", 63: "青海",
                        64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门",
                        91: "国外"
                    }
                    var idcard_array = new Array();
                    idcard_array = idNum.split("");
                    //地区检验
                    if (area[parseInt(idNum.substr(0, 2))] == null) {
                        result.msg = "身份证地区非法";
                        result.success = false;
                        break;
                    }
                    //出生日期正确性检验
                    var a = idNum.match(re);
                    if (a != null) {
                        if (len == 15) {
                            var DD = new Date("19" + a[3] + "/" + a[4] + "/" + a[5]);
                            var flag = DD.getYear() == a[3] && (DD.getMonth() + 1) == a[4] && DD.getDate() == a[5];
                        }
                        else if (len == 18) {
                            var DD = new Date(a[3] + "/" + a[4] + "/" + a[5]);
                            var flag = DD.getFullYear() == a[3] && (DD.getMonth() + 1) == a[4] && DD.getDate() == a[5];
                        }
                        if (!flag) {
                            result.msg = "身份证出生日期不对";
                            result.success = false;
                            break;
                        }
                        //检验校验位
                        if (len == 18) {
                            S = (parseInt(idcard_array[0]) + parseInt(idcard_array[10])) * 7
                                + (parseInt(idcard_array[1]) + parseInt(idcard_array[11])) * 9
                                + (parseInt(idcard_array[2]) + parseInt(idcard_array[12])) * 10
                                + (parseInt(idcard_array[3]) + parseInt(idcard_array[13])) * 5
                                + (parseInt(idcard_array[4]) + parseInt(idcard_array[14])) * 8
                                + (parseInt(idcard_array[5]) + parseInt(idcard_array[15])) * 4
                                + (parseInt(idcard_array[6]) + parseInt(idcard_array[16])) * 2
                                + parseInt(idcard_array[7]) * 1
                                + parseInt(idcard_array[8]) * 6
                                + parseInt(idcard_array[9]) * 3;

                            Y = S % 11;
                            M = "F";
                            JYM = "10X98765432";
                            M = JYM.substr(Y, 1); //判断校验位

                            //检测ID的校验位
                            if (M == idcard_array[17]) {
                                result.success = true;
                                break;
                            }
                            else {
                                result.msg = "身份证号码校验错误";
                                result.success = false;
                                break;
                            }
                        }

                    } else {
                        result.msg = "身份证含有非法字符";
                        result.success = false;
                        break;
                    }
                default:
                    result.success = value != null && value != ""; //默认为非空验证
                    result.msg = "不允许为空，请输入具体的数据！";
            }
            result.msg = jQuery.usi.core.isNullOrEmpty(config.msg) ? result.msg : config.msg;
            return result;
        }
    },
    //根据导航UNID,导航类型获取操作列表
    getOperateListByNavigationUnid: function (type, roleNavigationUnid, callback) {
        jQuery.usi.core.postCache("/Index/GetOperateListByNavigationUnid?type=" + type + "&roleNavigationUnid=" + (jQuery.usi.core.isNullOrEmpty(roleNavigationUnid) ? jQuery.usi.core.getURLParam("getOperateWhereValue") : roleNavigationUnid), { url: location.pathname }, false, function (data) {
            if (!jQuery.usi.core.isNullOrEmpty(callback)) {
                callback(data.data);
            }
        });
    },
    getUuid: function (len, radix) {
        var _return;
        jQuery.usi.core.post("/Base/GetGuid", { Len: len, Radix: radix }, true, function (data) {
            _return = data.data;
        });
        return _return;
    },
    dataTablesLang: {
        "sProcessing": "处理中...",
        "sLengthMenu": "每页 _MENU_ 项",
        "sZeroRecords": "没有匹配结果",
        "sInfo": "当前显示第 _START_ 至 _END_ 项，共 _TOTAL_ 项。",
        "sInfoEmpty": "当前显示第 0 至 0 项，共 0 项",
        "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
        "sInfoPostFix": "",
        "sSearch": "搜索:",
        "sUrl": "",
        "sEmptyTable": "表中数据为空",
        "sLoadingRecords": "载入中...",
        "sInfoThousands": ",",
        "oPaginate": {
            "sFirst": "首页",
            "sPrevious": "上页",
            "sNext": "下页",
            "sLast": "末页",
            "sJump": "跳转"
        }
    },
    bindDataTable: {
        loadData: function (config) {
            config.isLoadOperate = config.isLoadOperate != null ? config.isLoadOperate : true; //是否加载操作
            config.getOperateWhereValue = config.getOperateWhereValue == null ? "" : config.getOperateWhereValue;//获取系统操作条件值
            config.customOperate = config.customOperate != null ? config.customOperate : []; //自定义操作对象
            config.pageSize = config.pageSize == null ? 10 : config.pageSize;//分页条数
            config.isShowPage = config.isShowPage != null ? config.isShowPage : true; //是否显示分页
            config.searchWhereForm = config.searchWhereForm == null ? {} : config.searchWhereForm;//搜索条件存放form
            config.rowSelectClass = config.rowSelectClass != null ? config.rowSelectClass : "";
            config.searchWhereForm.array = [];
            config.callback = config.callback;
            config.rowcallback = config.rowCallback;
            config.onCheckClick = config.onCheckClick;
            config.onParam = config.param;
            config.param = {};
            config.operateParam = config.operateParam != null ? config.operateParam : {};
            if (config.id.indexOf("#") < 0) {
                config.id = "#" + config.id;
            }
            //获取条件
            if (!jQuery.usi.core.isNullOrEmpty(config.searchWhereForm) && !jQuery.usi.core.isNullOrEmpty(config.searchWhereForm.formId)) {
                if (config.searchWhereForm.formId.indexOf("#") < 0) {
                    config.searchWhereForm.formId = "#" + config.searchWhereForm.formId;
                }
                $(config.searchWhereForm.formId).find("input[type='text'],input[type='hidden'],select").each(function (index, item) {
                    config.searchWhereForm.array.push($(item));
                });
                if (!jQuery.usi.core.isNullOrEmpty(config.searchWhereForm.searchId)) {
                    if (config.searchWhereForm.searchId.indexOf("#") < 0) {
                        config.searchWhereForm.searchId = "#" + config.searchWhereForm.searchId;
                    }
                    //  
                    $(config.searchWhereForm.searchId).unbind("click");
                    $(config.searchWhereForm.searchId).bind("click", function () {
                        // 
                        jQuery.usi.tools.bindDataTable.refreshData(config.id);
                    });
                }
                $(config.searchWhereForm.formId).find("input[type='text']").bind("keyup", function (item) {
                    if (item.keyCode == 13) {
                        jQuery.usi.tools.bindDataTable.refreshData(config.id);
                    }
                })
                $(config.searchWhereForm.formId).find("input[type='text']").bind("keypress", function (item) {
                    if (item.keyCode == 13) {
                        return false;
                    }
                })
            }
            //是否加载事件
            if (config.isLoadOperate != null && !config.isLoadOperate) {
                jQuery.usi.tools.bindDataTable.load(config);
            } else {
                //加载gridEvent 
                jQuery.usi.tools.getOperateListByNavigationUnid("Grid", config.getOperateWhereValue, function (operateData) {
                    $.each(operateData, function (index, operateItem) {
                        config.customOperate.push({ name: operateItem.name, click: jQuery.usi.core.parseEvent(operateItem.event), formula: operateItem.formula });
                    });
                    jQuery.usi.tools.bindDataTable.load(config);
                });
            }
        },
        load: function (config) {
            //查询
            var queryData = {
                pageSize: config.pageSize,
                currentPage: 1,
                query: {
                    criteriaList: []
                }
            };
            var table = $(config.id);
            var dt = null;

            if (!jQuery.usi.core.isNullOrEmpty(table.attr("guid")) && jQuery.usi.core.dataGridHeadCache != null && jQuery.usi.core.dataGridHeadCache.length > 0) {
                $.each(jQuery.usi.core.dataGridHeadCache, function (index, item) {
                    if (item.guid == table.attr("guid")) {
                        dt = item.data;
                        return false;
                    }
                });
            }
            if (dt == null) {
                //生成列表表头字段信息与各列重新渲染
                var scolumns = [];
                var scolumnDefs = [];
                scolumnDefs.push({
                    "targets": 'nosort',  //列的样式名
                    "orderable": false    //包含上样式名‘nosort’的禁止排序
                });
                var guid = jQuery.usi.core.newGuid();
                table.attr("guid", guid); //设置GUID
                var docTr = table.find("thead tr:first");
                var docTdArray = docTr.find("th");
                //从写tr和td对象
                var tr = $(document.createElement("tr"));
                var tdArray = [];
                $.ajaxSetup({ async: false }); //设置同步
                $.each(docTdArray, function (index, item) {
                    var itemTd = $(item);
                    var thObj = jQuery.usi.tools.bindDataTable.getThObj(itemTd);
                    if (!jQuery.usi.core.isNullOrEmpty(thObj.dataName)) {
                        if (!jQuery.usi.core.isNullOrEmpty(thObj.className)) {
                            scolumns.push({
                                "data": thObj.dataName,
                                "className": thObj.className
                            });
                        } else {
                            scolumns.push({ "data": thObj.dataName });
                        }
                    }
                    if (thObj.type == "checkbox") {
                        var checkObj = $("<input type='checkbox' headfieldname='" + thObj.dataName + "' />");
                        checkObj.bind("click", function () {
                            var check = $(this);
                            table.find("tbody tr td input[headfieldname='" + check.attr("headfieldname") + "']").removeAttr("checked");
                            table.find("tbody tr td input[headfieldname='" + check.attr("headfieldname") + "']").prop("checked", check.prop("checked"));
                            $.each(table.find("tbody tr td input[headfieldname='" + check.attr("headfieldname") + "']"), function (cindex, citem) {
                                if (jQuery.usi.core.isMethod(config.onCheckClick)) {
                                    var data = $(config.id).DataTable().row($(citem).parents('tr')).data();
                                    config.onCheckClick(data, $(citem));
                                }
                            });

                        });
                        itemTd.html(checkObj);
                    } else if (thObj.type == "radio") {
                        var checkObj = $("<input type='radio' headfieldname='" + thObj.dataName + "' />");
                        itemTd.html(checkObj);
                    }
                    scolumnDefs.push({
                        "targets": [index],
                        "render": function (data, type, item) {
                            var returnValue = "";
                            if (thObj.type == "checkbox") {
                                returnValue = ("<input type='checkbox' class='checkchild' headfieldname='" + thObj.dataName + "' value='" + data + "' />");
                            } else if (thObj.type == "radio") {
                                returnValue = ("<input type='radio' class='checkchild' headfieldname='" + thObj.dataName + "' name='" + thObj.dataName + "' value='" + data + "'/>");
                            } else if (thObj.type == "operate") {
                                //操作处理
                                if (config.customOperate != null && config.customOperate.length > 0) {
                                    $.each(config.customOperate, function (index, event) {
                                        var a = ("<a class=\"btn btn-secondary mar_r10\" id=\"" + config.id.replace("#", "") + event.name + "\" href=\"javascript:;\" >" + event.name + "</a>");
                                        if (!jQuery.usi.core.isNullOrEmpty(event.formula)) {
                                            var formula = event.formula;
                                            var eventBool;
                                            try {
                                                eventBool = eval("item." + formula);
                                            } catch (e) {
                                                eventBool = eval(formula);
                                            }
                                            if (eventBool) {
                                                returnValue = returnValue + a;
                                            }
                                        } else {
                                            returnValue = returnValue + a;
                                        }
                                    });
                                }
                            } else if (thObj.type == "href") {
                                //处理渲染
                                var temp = data;
                                if (!jQuery.usi.core.isNullOrEmpty(thObj.dataValue)) {
                                    try {
                                        temp = eval("item." + thObj.dataValue);
                                    } catch (e) { }
                                }
                                returnValue = ("<a href='#' style='color:red;' onclick='" + thObj.renderFun + "(\"" + temp + "\")'>" + data + "</a>");
                            } else {
                                //处理渲染
                                if (!jQuery.usi.core.isNullOrEmpty(thObj.dataName)) {
                                    if (thObj.dataName.indexOf(".") >= 0) {
                                        try {
                                            data = eval("item." + thObj.dataName);
                                        } catch (e) { }
                                    }
                                }
                                returnValue = jQuery.usi.core.isNullOrEmpty(data) ? "" : data;
                                if (!jQuery.usi.core.isNullOrEmpty(thObj.renderFun)) {
                                    thObj.renderFun = jQuery.usi.core.parseEvent(thObj.renderFun);
                                    returnValue = thObj.renderFun(item);
                                }
                                if (!jQuery.usi.core.isNullOrEmpty(thObj.dataSource)) {
                                    returnValue = jQuery.usi.core.getDataSourceName(returnValue, thObj.dataSource); //数据绑定
                                }
                                if (thObj.dataType == "datetime") {
                                    if (!jQuery.usi.core.isNullOrEmpty(thObj.dataFormat)) {
                                        returnValue = jQuery.usi.core.formatDate(returnValue, thObj.dataFormat);
                                    } else {
                                        returnValue = jQuery.usi.core.formatDate(returnValue);
                                    }
                                }
                                if (jQuery.usi.core.isDate(returnValue)) {
                                    returnValue = jQuery.usi.core.formatDate(returnValue);
                                }
                                if (!jQuery.usi.core.isNullOrEmpty(thObj.stringLength) && !jQuery.usi.core.isNullOrEmpty(returnValue)) {
                                    returnValue = jQuery.usi.core.setString(returnValue, thObj.stringLength); //设置字符长度
                                }
                                if (!jQuery.usi.core.isNullOrEmpty(thObj.suffix)) {
                                    returnValue = returnValue + thObj.suffix;
                                }
                            }
                            return returnValue;
                        }
                    });
                    tdArray.push(thObj);
                });
                $.ajaxSetup({ async: true }); //设置异步
                //jQuery.usi.core.dataGridHeadCache.push({ guid: guid, data: tdArray }); //放入缓存
                var dt = $(config.id).dataTable({
                    language: jQuery.usi.tools.dataTablesLang,  //提示信息
                    autoWidth: false,  //禁用自动调整列宽
                    //  stripeClasses: ["odd", "even"],  //为奇偶行加上样式，兼容不支持CSS伪类的场合
                    processing: false,  //隐藏加载提示,自行处理
                    serverSide: true,  //启用服务器端分页
                    searching: false,  //禁用原生搜索
                    paging: config.isShowPage,
                    lengthChange: true,
                    pageLength: queryData.pageSize,
                    orderMulti: false,  //启用多列排序
                    ordering: false,
                    order: [],  //取消默认排序查询,否则复选框一列会出现小箭头
                    renderer: "bootstrap",  //渲染样式：Bootstrap和jquery-ui
                    pagingType: "simple_numbers",  //分页样式：simple,simple_numbers,full,full_numbers
                    ajax: function (data, callback, settings) {
                        queryData.query = jQuery.usi.tools.bindDataTable.getsearchWhereForm(config.searchWhereForm.array);
                        if (!jQuery.usi.core.isNullOrEmpty(data.length) && data.length != -1) {
                            queryData.pageSize = data.length;
                            queryData.currentPage = (data.start / data.length) + 1;//当前页码
                        }
                        if (jQuery.usi.core.isMethod(config.onParam)) {
                            config.param = config.onParam();
                        }
                        config.param.queryData = jQuery.toJSON(queryData);
                        //封装请求参数
                        jQuery.usi.core.post(config.url, config.param, false, function (result) {
                            $(config.id + " tbody").html("");
                            var returnData = {};
                            returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
                            returnData.recordsTotal = result.data.totalCount;//返回数据全部记录
                            returnData.recordsFiltered = result.data.totalCount;//后台不实现过滤功能，每次查询均视作全部结果
                            returnData.data = jQuery.usi.core.isNullOrEmpty(result.data.data) ? [] : result.data.data;//返回的数据列表
                            callback(returnData);
                            //操作处理
                            if (config.customOperate != null && config.customOperate.length > 0) {
                                $.each(config.customOperate, function (index, event) {
                                    $(config.id + ' tbody').off('click', 'a' + config.id + event.name);
                                    $(config.id + ' tbody').on('click', 'a' + config.id + event.name, function () {
                                        var data = $(config.id).DataTable().row($(this).parents('tr')).data();
                                        if (jQuery.usi.core.isNullOrEmpty(config.operateParam)) {
                                            event.click(data);
                                        } else {
                                            event.click(data, config.operateParam);
                                        }

                                    });
                                });
                            }
                            if (jQuery.usi.core.isMethod(config.onCheckClick)) {
                                var inputArray = $(config.id + " tbody tr td input[headfieldname='unid']");
                                var resultValue = [];
                                $.each(inputArray, function (index, item) {
                                    var data = $(config.id).DataTable().row($(item).parents('tr')).data();
                                    $(item).unbind("click");
                                    $(item).bind("click", function () {
                                        config.onCheckClick(data, $(item));
                                    });
                                });
                            }
                            $(config.id + " tbody").off("click", "tr");
                            //选中行事件
                            $(config.id + " tbody").on("click", "tr", function (objTr) {
                                if (!jQuery.usi.core.isNullOrEmpty(objTr.target) && objTr.target.nodeName == "TD") {
                                    var check = $(this).find(".checkchild").prop("checked");
                                    if (check && check == true) {
                                        $(this).find('.checkchild').prop("checked", false);
                                    } else {
                                        $(this).find('.checkchild').prop("checked", true);
                                    }
                                    if (jQuery.usi.core.isMethod(config.onCheckClick)) {
                                        var data = $(config.id).DataTable().row($(this).find('.checkchild').parents('tr')).data();
                                        config.onCheckClick(data, $(this).find('.checkchild'));
                                    }
                                }
                            });
                            if (jQuery.usi.core.isMethod(config.callback)) {
                                config.callback(result.data, settings);
                            }
                        });
                    },
                    rowCallback: function (row, data, index) {
                        if (jQuery.usi.core.isMethod(config.rowCallback)) {
                            config.rowCallback(row, data, index);
                        }
                    },
                    //列表表头字段
                    columns: scolumns,
                    //各列重新渲染
                    columnDefs: scolumnDefs

                }).api();
                jQuery.usi.core.dataGridHeadCache.push({ guid: guid, data: dt }); //放入缓存
            } else {
                $(config.id).dataTable().fnDraw(false);
            }
        },
        getThObj: function (item) {
            var thObj = {
                dataName: item.attr("dataname"),
                dataValue: item.attr("datavalue"),
                className: item.attr("classname"),
                stringLength: item.attr("stringlength"), //字符长度                
                type: item.attr("type"), //操作类型[checkbox,radio,operatelist]
                dataType: item.attr("datatype"), //dateTime,string
                dataFormat: item.attr("dateformat"), //时间格式 当DataType=datetime 有效
                dataSourceUrl: item.attr("datasourceurl"), //数据源(地址)
                dataSourceKey: item.attr("datasourcekey"), //数据源(数据字典)
                renderFun: item.attr("renderfun"), //渲染调用某个方法
                suffix: item.attr("suffix"), //渲染调用某个方法
                dataSource: null//数据源 当DataSourceUrl或DataSourceKey不等于空 有效
            };

            if (!jQuery.usi.core.isNullOrEmpty(thObj.dataSourceUrl)) {
                jQuery.usi.core.postCache(thObj.dataSourceUrl, null, true, function (resultDataSource) {
                    thObj.dataSource = resultDataSource.data;
                });
            }
            if (!jQuery.usi.core.isNullOrEmpty(thObj.dataSourceKey)) {
                try {
                    thObj.dataSource = eval("Data_" + thObj.dataSourceKey);
                } catch (e) {
                    thObj.dataSource = [];
                }
            }
            if (jQuery.usi.core.isNullOrEmpty(thObj.suffix)) {
                thObj.suffix = "";
            }
            return thObj;
        },
        getsearchWhereForm: function (searchFormArray) {
            var query = { criteriaList: [] };
            if (!jQuery.usi.core.isNullOrEmpty(searchFormArray) && searchFormArray.length > 0) {
                $.each(searchFormArray, function (index, item) {
                    var value = item.val();
                    if (!jQuery.usi.core.isNullOrEmpty(value)) {
                        var criteria = { name: "", value: "", operate: "", dataType: "", endSuffix: "" };
                        criteria.name = jQuery.usi.core.isNullOrEmpty(item.attr("name")) ? item.attr("Name") : item.attr("name"); //名称
                        if (!jQuery.usi.core.isNullOrEmpty(criteria.name)) {
                            criteria.dataType = item.attr("datatype"); //数据类型
                            criteria.value = value;
                            criteria.suffix = item.attr("suffix"); //查询后缀 
                            if (!jQuery.usi.core.isNullOrEmpty(criteria.suffix)) {
                                criteria.value += criteria.suffix;
                            }
                            if (item.length > 0 && item[0].type == "select-one") {
                                criteria.operate = "Equal";
                            } else if (criteria.dataType == "DateTime" && jQuery.usi.core.isNullOrEmpty(item.attr("operate")))//如果是时间类型 只允许为相等
                            {
                                criteria.operate = "Equal";
                            } else {
                                criteria.operate = item.attr("operate"); //操作符
                            }
                            if (jQuery.usi.core.isNullOrEmpty(criteria.operate)) {//默认为模糊查询
                                criteria.operate = "Like";
                                criteria.value = ("%" + value + "%");
                            }
                            query.criteriaList.push(criteria);
                        }
                    }
                });
                return query;
            }
        },
        getIds: function (tableId, fieldName) {
            if (tableId.indexOf("#") < 0) {
                tableId = "#" + tableId;
            }
            fieldName = jQuery.usi.core.isNullOrEmpty(fieldName) ? "unid" : fieldName;
            var inputArray = $(tableId + " tbody tr td input[headfieldname='" + fieldName + "']:checked");
            var resultValue = [];
            $.each(inputArray, function (index, item) {
                if (!jQuery.usi.core.isNullOrEmpty($(item).val())) {
                    resultValue.push($(item).val());
                }
            });
            return resultValue.join(',');
        },
        getCheckBoxItems: function (tableId, fieldName) {
            if (tableId.indexOf("#") < 0) {
                tableId = "#" + tableId;
            }
            fieldName = jQuery.usi.core.isNullOrEmpty(fieldName) ? "unid" : fieldName;
            var inputArray = $(tableId + " tbody tr td input[headfieldname='" + fieldName + "']:checked");
            var resultValue = [];
            $.each(inputArray, function (index, item) {
                var data = $(tableId).DataTable().row($(item).parents('tr')).data();
                resultValue.push(data);
            });
            return resultValue;
        },
        deleteData: function (config) {
            if (config.id.indexOf("#") < 0) {
                config.id = "#" + config.id;
            }
            var id = jQuery.usi.tools.bindDataTable.getIds(config.id, config.fieldName);
            if (id == "") {
                layer.alert("请选择您要删除的记录！");
            } else {
                jQuery.usi.core.deletePost(config.url, { Ids: id }, function (data) {
                    $(config.id).dataTable().fnDraw(false);
                    if (jQuery.usi.core.isMethod(config.callback)) {
                        config.callback(data);
                    }
                });
            }
        },
        refreshData: function (id) {
            if (id.indexOf("#") < 0) {
                id = "#" + id;
            }
            $(id).dataTable().fnDraw(false);
        }

    },
    //加载操作栏
    loadToolbar: function (getOperateWhereValue, id) {
        var toolbar;
        if (id.indexOf("#") >= 0) {
            toolbar = $(id);
        } else {
            toolbar = $("#" + id);
        }
        if (toolbar.length != 0) {
            //  toolbar.html("操作");
            jQuery.usi.tools.getOperateListByNavigationUnid("Toolbar", getOperateWhereValue, function (data) {
                if (toolbar.attr("custom") == "true") {
                    $.each(data, function (index, item) {
                        var i = $('<input type="button" value="' + item.name + '" class="btn btn-secondary mar_r10">');
                        var event = jQuery.usi.core.parseEvent(item.event);
                        i.bind("click", function () {
                            event();
                        });
                        toolbar.append(i);
                    });
                } else {
                    if (jQuery.usi.core.isNullOrEmpty(data) || data.lenght == 0) {
                        toolbar.hide();
                    } else {
                        $.each(data, function (index, item) {
                            var i = $('<input type="button" value="' + item.name + '" class=" btn btn-secondary mar_r10">');
                            var event = jQuery.usi.core.parseEvent(item.event);
                            i.bind("click", function () {
                                event();
                            });
                            if (!jQuery.usi.core.isNullOrEmpty(item.formula)) {
                                var formula = item.formula;
                                var eventBool;
                                try {
                                    eventBool = eval("item." + formula);
                                } catch (e) {
                                    eventBool = eval(formula);
                                }
                                if (eventBool) {
                                    toolbar.append(i);
                                }
                            } else {
                                toolbar.append(i);
                            }
                        });
                    }
                }
            });
        }
    },
    bindDataForSelect: function (config, resultData) {
        config.text = jQuery.usi.core.isNullOrEmpty(config.text) ? "请选择" : config.text;
        var docElement = document.getElementById(config.id);
        var element = jQuery.usi.core.getJqueryById(config.id);
        element.html("");
        if (jQuery.usi.core.isNullOrEmpty(docElement)) return;
        if (docElement.type == "select-one") {
            if (config.isAll != null && config.isAll) {
                element.append("<option value=''>" + config.text + "</option>");
            }
            $.each(resultData, function (index, item) {
                var option = $(document.createElement("option"));
                if (item.selected || config.selectId == (jQuery.usi.core.isNullOrEmpty(config.idField) ? item.id : eval("item." + config.idField))) {
                    option.attr("selected", "selected");
                }
                if (!jQuery.usi.core.isNullOrEmpty(item.data)) {
                    option.data("dataObj", item.data);
                }
                option.attr("value", (jQuery.usi.core.isNullOrEmpty(config.idField) ? item.id : eval("item." + config.idField)));
                option.html((jQuery.usi.core.isNullOrEmpty(config.nameField) ? item.name : eval("item." + config.nameField)));
                element.append(option);
            });
            if (config.onChange != null) {
                element.bind("change", function () {
                    if (jQuery.usi.core.isMethod(config.onChange)) {
                        config.onChange(element.val(), element.find("option:selected").data("dataObj"));
                    }
                });
            }
            if (jQuery.usi.core.isMethod(config.callback)) {
                config.callback();
            }
        } else {
            if (config.isAll != null && config.isAll) {
                element.append("<option value=''>" + config.text + "</option>");
            }
            $.each(resultData, function (index, item) {
                var option = $(document.createElement("option"));
                if (item.selected || config.selectId == (jQuery.usi.core.isNullOrEmpty(config.idField) ? item.id : eval("item." + config.idField))) {
                    option.attr("selected", "selected");
                }
                if (!jQuery.usi.core.isNullOrEmpty(item.data)) {
                    option.data("dataObj", item.data);
                }
                option.attr("value", (jQuery.usi.core.isNullOrEmpty(config.idField) ? item.id : eval("item." + config.idField)));
                option.html((jQuery.usi.core.isNullOrEmpty(config.nameField) ? item.name : eval("item." + config.nameField)));
                element.append(option);
            });
            if (config.onChange != null) {
                element.bind("change", function () {
                    if (jQuery.usi.core.isMethod(config.onChange)) {
                        config.onChange(element.val(), element.find("option:selected").data("dataObj"));
                    }
                });
            }
            if (jQuery.usi.core.isMethod(config.callback)) {
                config.callback();
            }
        }
    },
    //数据绑定config = { url: 请求地址, param: 请求参数, id:元素ID,callback: 回调 };
    bindData: function (config) {
        var url = config.url;
        var param = config.param == null ? "" : config.param;
        config.isReadCache = config.isReadCache == null ? false : config.isReadCache;
        if (config.isReadCache) {
            jQuery.usi.core.postCache(url, param, false, function (resultData) {
                jQuery.usi.tools.bindDataForSelect(config, resultData.data);
            });
        } else {
            jQuery.usi.core.post(url, param, false, function (resultData) {
                jQuery.usi.tools.bindDataForSelect(config, resultData.data);
            });
        }
    },
    //数据绑定config = { url: 请求地址, param: 请求参数, id:元素ID,callback: 回调 };
    bindDataForJson: function (config) {
        var url = config.url;
        var param = config.param == null ? "" : config.param;
        config.isReadCache = config.isReadCache == null ? false : config.isReadCache;
        if (config.isReadCache) {
            jQuery.usi.core.postCache(url, param, true, function (resultData) {
                jQuery.usi.tools.bindDataForSelect(config, resultData);
            });
        } else {
            jQuery.usi.core.getJson(url, param, true, function (resultData) {
                if (!jQuery.usi.core.isNullOrEmpty(config.param)) {
                    resultData = resultData.filter(function (i, v) {
                        if ((eval("i." + config.param.id)) == config.param.value) {
                            return i;
                        }
                    });
                }
                jQuery.usi.tools.bindDataForSelect(config, resultData);
            });
        }
    },
    loading: {
        show: function (config) {
            if ($("#bonfire-pageloader").length > 0) {
                $("#bonfire-pageloader").show();
            } else {
                var loadDiv = $('<div id="bonfire-pageloader" style="text-align:center"></div>');
                var loadDiv2 = $('<div class="bonfire-pageloader-icon"></div>')
               // var svg = $('<svg version="1.1" x="0px" y="0px" width="5rem" height="5rem" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve"><path id="loading-12-icon" d="M291,82.219c0,16.568-13.432,30-30,30s-30-13.432-30-30s13.432-30,30-30S291,65.65,291,82.219zM261,404.781c-15.188,0-27.5,12.312-27.5,27.5s12.312,27.5,27.5,27.5s27.5-12.312,27.5-27.5S276.188,404.781,261,404.781zM361.504,113.167c-4.142,7.173-13.314,9.631-20.487,5.489c-7.173-4.141-9.631-13.313-5.49-20.487c4.142-7.173,13.314-9.631,20.488-5.489C363.188,96.821,365.645,105.994,361.504,113.167z M188.484,382.851c-14.348-8.284-32.697-3.368-40.98,10.98c-8.285,14.349-3.367,32.696,10.98,40.981c14.35,8.283,32.697,3.367,40.98-10.981C207.75,409.482,202.834,391.135,188.484,382.851z M421.33,184.888c-8.368,4.831-19.07,1.965-23.901-6.404c-4.832-8.368-1.965-19.07,6.404-23.902c8.368-4.831,19.069-1.964,23.9,6.405C432.566,169.354,429.699,180.056,421.33,184.888zM135.399,329.767c-8.285-14.35-26.633-19.266-40.982-10.982c-14.348,8.285-19.264,26.633-10.979,40.982c8.284,14.348,26.632,19.264,40.981,10.98C138.767,362.462,143.683,344.114,135.399,329.767z M436.031,277.249c-11.044,0-20-8.953-20-19.999c0-11.045,8.955-20.001,20.001-20.001c11.044,0,19.999,8.955,19.999,20.002C456.031,268.295,447.078,277.249,436.031,277.249z M115.97,257.251c-0.001-16.57-13.433-30.001-30.001-30.002c-16.568,0.001-29.999,13.432-30,30.002c0.001,16.566,13.433,29.998,30.001,30C102.538,287.249,115.969,273.817,115.97,257.251zM401.333,364.248c-10.759-6.212-14.446-19.97-8.234-30.73c6.212-10.759,19.971-14.446,30.731-8.233c10.759,6.211,14.445,19.971,8.232,30.73C425.852,366.774,412.094,370.46,401.333,364.248z M135.398,184.736c8.285-14.352,3.368-32.698-10.98-40.983c-14.349-8.283-32.695-3.367-40.981,10.982c-8.282,14.348-3.366,32.696,10.981,40.981C108.768,204,127.115,199.082,135.398,184.736z M326.869,421.328c-6.902-11.953-2.807-27.242,9.148-34.145s27.243-2.806,34.146,9.149c6.902,11.954,2.806,27.243-9.15,34.145C349.059,437.381,333.771,433.284,326.869,421.328zM188.482,131.649c14.352-8.286,19.266-26.633,10.982-40.982c-8.285-14.348-26.631-19.264-40.982-10.98c-14.346,8.285-19.264,26.633-10.98,40.982C155.787,135.017,174.137,139.932,188.482,131.649z"></svg>');
               // loadDiv2.append(svg);
                loadDiv.append(loadDiv2);
                $("body").append(loadDiv);
            }
        },
        hide: function () {
            $("#bonfire-pageloader").hide();
        },
        remove: function () {
            $("#bonfire-pageloader").remove();
        }
    },
    selectTemplate: function (newConfig) {
        var config = {
            id: "",
            hideId: "",
            title: "",
            url: "",
            callback: function () {

            }
        };
        $.extend(true, config, newConfig);
        var input = jQuery.usi.core.getJqueryById(config.id).addClass("dataSelect").attr("readonly", "readonly");
        var hideInput = jQuery.usi.core.getJqueryById(config.hideId).attr("autocomplete", "off");
        input.attr("autocomplete", "off"); //清楚浏览器自动填充的缓存
        input.bind("click", function () {
            jQuery.usi.core.layer_show({
                type: 1,
                title: config.title,
                content: config.url,
                success: function () {
                    if (jQuery.usi.core.isMethod(config.callback)) {
                        var layerIndex = layer.index;
                        config.callback(layerIndex)
                    }
                }
            });
        })
    }
};
//设置页面为只读

function onlyRead(id) {
    if (jQuery.usi.core.isNullOrEmpty(id)) id = "ViewForm";
    var viewid = document.getElementById(id);
    var inputs = viewid.getElementsByTagName("input");
    var selects = viewid.getElementsByTagName("select");
    var textarea = viewid.getElementsByTagName('textarea');
    var radio = viewid.getElementsByTagName("radio");
    var checkbox = viewid.getElementsByTagName("checkbox");
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].type != "button") {
            inputs[i].setAttribute("disabled", true);
        }
    }
    for (var i = 0; i < selects.length; i++) {
        selects[i].setAttribute("disabled", true);
    }
    for (var i = 0; i < radio.length; i++) {
        radio[i].setAttribute("disabled", true);
    }
    for (var i = 0; i < checkbox.length; i++) {
        checkbox[i].setAttribute("disabled", true);
    }
    for (var i = 0; i < textarea.length; i++) {
        textarea[i].setAttribute("disabled", true);
    }
}
//datahelper
var DateHelper = {
    GetYear: function () {
        return (new Date()).getFullYear();
    },
    GetMonth: function () {
        return (new Date()).getMonth() + 1;
    },
    GetGreaterDate: function () {
        //获取大于当前日期的时间
        var dt = new Date().format("yyyy-M-d").split("-");
        dt = new Date(dt[0] * 1, dt[1] * 1 - 1, parseInt(dt[2]) + parseInt(1));
        dt = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate());
        dt = dt.getFullYear() + "-" + (dt.getMonth() + 1) + "-" + dt.getDate();
        return [dt, "9999-1-1"];
    },
    GetLessOrEqualDate: function () {
        //获取小于当前日期的时间
        var dt = new Date().format("yyyy-M-d").split("-");
        dt = new Date(dt[0] * 1, dt[1] * 1 - 1, parseInt(dt[2]) + parseInt(-1));
        dt = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate());
        dt = dt.getFullYear() + "-" + (dt.getMonth() + 1) + "-" + dt.getDate();
        return ["0001-1-1", dt];
    }
};
$(function () {
    $(".seachmain").css("display", "none");
    $(".panel-header span").addClass("zkon");
    $(".panel-header span").click(function (event) {
        xspan = $(this).find("i");
        if ($(this).hasClass("zkon")) {
            xspan.text("收起查询");
            $(".seachmain").slideDown();
            $(this).removeClass("zkon")
        } else {
            xspan.text("查看查询");
            $(".seachmain").slideUp();
            $(this).addClass("zkon")
        }
    });
});
//全屏
